package sqs;



import org.apache.log4j.Logger;

import com.xerox.amazonws.sqs2.MessageQueue;
import com.xerox.amazonws.sqs2.Message;
import com.xerox.amazonws.sqs2.SQSUtils;

/**
 * This sample application retrieves (dequeues) a message from the queue specified by
 * the value of the queuename parameter. If successful, it deletes the message from the queue.
 * On error, it retries a number of times.
 */
public class DequeueSample {
        private static Logger log = Logger.getLogger(DequeueSample.class);
        final static String AWSAccessKeyId = "SOMETHING";
        final static  String SecretAccessKey = "SOMETHING";
        public static void main( String[] args ) {
        	

                int count = 0;
                try {
                        if (args.length < 1) {
                                log.error("usage: DequeueSample <queueId>");
                        }
                        String queueName = "hum11queue";

                        // Retrieve the message queue object (by name).
                        MessageQueue msgQueue = SQSUtils.connectToQueue(queueName, AWSAccessKeyId, SecretAccessKey);

                        // Try to retrieve (dequeue) the message, and then delete it.
                        Message msg = null;
                        while (true) {
                                msg = msgQueue.receiveMessage();
                                if (msg == null) {
                                        log.debug("nothing... retrying");
                                        try { Thread.sleep(3000); } catch (Exception ex) {}
                                        continue;
                                }
                                String text = msg.getMessageBody();
                                String md5 = msg.getBodyMD5();
                                String id = msg.getMessageId();
                                String reqHandle = msg.getReceiptHandle();
                                log.info("MSG body =====  "+text);
                                log.info("MSG id =====  "+id);
                                log.info("MSG md5 =====  "+md5);
                                log.info("MSG reqHandle =====  "+reqHandle);
                                
                                msgQueue.deleteMessage(msg);
                                log.info( "Deleted message id " + msg.getMessageId());
                                count++;
                        }
                } catch ( Exception ex ) {
                        log.error( "EXCEPTION", ex );
                }
                log.debug("Deleted "+count+" messages");
        }
}
